<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>我的 - YOLOv8视频智能检测</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#2563eb',
                        secondary: '#4f46e5',
                        danger: '#ef4444',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        body { font-family: 'Inter', system-ui, sans-serif; background-color: #f8fafc; }
        html { scroll-behavior: smooth; }
        .shadow-custom { box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08); }
        .fade-in { animation: fadeIn 0.3s ease-out; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }
        .menu-item-active { background-color: #eff6ff; color: #2563eb; }
        .transition-all { transition: all 0.3s ease; }
        .hidden { display: none !important; }
        /* 加载状态样式 */
        .btn-loading { position: relative; pointer-events: none; }
        .btn-loading::after {
            content: '';
            position: absolute;
            top: 50%;
            right: 12px;
            width: 16px;
            height: 16px;
            border: 2px solid rgba(255,255,255,0.5);
            border-top-color: #fff;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
            transform: translateY(-50%);
        }
        @keyframes spin { to { transform: translateY(-50%) rotate(360deg); } }

        /* 自定义弹窗样式 */
        .custom-modal-backdrop {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }
        .custom-modal-backdrop.show {
            opacity: 1;
            visibility: visible;
        }
        .custom-modal {
            background: white;
            border-radius: 8px;
            padding: 24px;
            width: 90%;
            max-width: 300px;
            text-align: center;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            transform: translateY(-20px);
            transition: transform 0.3s ease;
        }
        .custom-modal-backdrop.show .custom-modal {
            transform: translateY(0);
        }
        .modal-message {
            margin: 16px 0;
            color: #333;
            font-size: 16px;
        }
        .modal-confirm {
            background: #2563eb;
            color: white;
            border: none;
            padding: 8px 24px;
            border-radius: 4px;
            cursor: pointer;
            margin-top: 8px;
            transition: background 0.2s;
        }
        .modal-confirm:hover {
            background: #1d4ed8;
        }
    </style>
</head>
<body class="min-h-screen flex flex-col bg-gray-50">
<!-- 自定义弹窗 -->
<div class="custom-modal-backdrop" id="customModal">
    <div class="custom-modal">
        <i class="fa fa-exclamation-circle text-danger text-2xl"></i>
        <div class="modal-message" id="modalMessage"></div>
        <button class="modal-confirm" id="modalConfirm">确定</button>
    </div>
</div>

<main class="flex-grow container mx-auto px-4 py-8">
    <div class="max-w-6xl mx-auto">
        <!-- 用户信息卡片 -->
        <section class="mb-8">
            <div class="bg-white rounded-xl shadow-custom p-8">
                <div class="flex flex-col items-center">
                    <div class="w-24 h-24 rounded-full bg-primary/10 flex items-center justify-center mb-4">
                        <i class="fa fa-user text-4xl text-primary"></i>
                    </div>
                    <h2 id="profile-username" class="text-xl font-bold mb-2">未登录</h2>
                    <p id="profile-status" class="text-gray-500 mb-6">登录后享受更多功能</p>
                    <div id="profile-actions" class="w-full max-w-xs">
                        <button id="login-btn" class="px-8 py-3 rounded-lg bg-primary text-white hover:bg-primary/90 transition-colors mb-4 w-full">
                            <i class="fa fa-sign-in mr-2"></i>登录/注册
                        </button>
                        <div id="logged-in-content" class="hidden">
                            <div class="bg-gray-50 rounded-lg p-6 mb-6">
                                <h3 class="text-lg font-semibold mb-4">账户信息</h3>
                                <div class="space-y-3">
                                    <div class="flex justify-between">
                                        <span class="text-gray-600">用户名：</span>
                                        <span id="account-name" class="font-medium"></span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span class="text-gray-600">会员等级：</span>
                                        <span class="font-medium">普通用户</span>
                                    </div>
                                    <div class="flex justify-between">
                                        <span class="text-gray-600">处理次数：</span>
                                        <span id="detection-count" class="font-medium">0次</span>
                                    </div>
                                </div>
                            </div>
                            <button id="logout-btn" class="px-8 py-3 rounded-lg border border-gray-300 text-gray-700 hover:bg-gray-50 transition-colors w-full">
                                <i class="fa fa-sign-out mr-2"></i>退出登录
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 统计数据 -->
        <section id="stats-section" class="mb-8 hidden">
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div class="bg-white rounded-xl shadow-md p-5">
                    <div class="text-3xl font-bold text-blue-600 mb-1">28</div>
                    <div class="text-sm text-gray-600">检测总数</div>
                </div>
                <div class="bg-white rounded-xl shadow-md p-5">
                    <div class="text-3xl font-bold text-yellow-500 mb-1">3</div>
                    <div class="text-sm text-gray-600">待处理</div>
                </div>
                <div class="bg-white rounded-xl shadow-md p-5">
                    <div class="text-3xl font-bold text-green-600 mb-1">25</div>
                    <div class="text-sm text-gray-600">已完成</div>
                </div>
                <div class="bg-white rounded-xl shadow-md p-5">
                    <div class="text-3xl font-bold text-red-500 mb-1">7</div>
                    <div class="text-sm text-gray-600">危险预警</div>
                </div>
            </div>
        </section>

        <!-- 功能区域 -->
        <section class="grid grid-cols-1 md:grid-cols-4 gap-6">
            <!-- 侧边菜单 -->
            <div id="menu-section" class="md:col-span-1 hidden">
                <div class="bg-white rounded-xl shadow-md p-4">
                    <h3 class="text-lg font-semibold mb-4 text-gray-800 px-3">功能菜单</h3>
                    <ul class="space-y-2">
                        <li><a href="#detection-history" class="menu-item menu-item-active flex items-center py-3 px-3 rounded-lg transition-all"><i class="fa fa-history w-6 text-center mr-3"></i><span>检测历史</span></a></li>
                        <li><a href="#saved-reports" class="menu-item flex items-center py-3 px-3 rounded-lg text-gray-700 hover:bg-gray-50 transition-all"><i class="fa fa-file-text-o w-6 text-center mr-3"></i><span>保存的报告</span></a></li>
                        <li><a href="#account-settings" class="menu-item flex items-center py-3 px-3 rounded-lg text-gray-700 hover:bg-gray-50 transition-all"><i class="fa fa-cog w-6 text-center mr-3"></i><span>账户设置</span></a></li>
                        <li><a href="./faq.html" class="menu-item flex items-center py-3 px-3 rounded-lg text-gray-700 hover:bg-gray-50 transition-all"><i class="fa fa-question-circle w-6 text-center mr-3"></i><span>帮助中心</span></a></li>
                        <li><a href="#about-us" class="menu-item flex items-center py-3 px-3 rounded-lg text-gray-700 hover:bg-gray-50 transition-all"><i class="fa fa-info-circle w-6 text-center mr-3"></i><span>关于我们</span></a></li>
                        <li class="mt-4 pt-4 border-t border-gray-100">
                            <button id="menu-logout-btn" class="menu-item w-full flex items-center py-3 px-3 rounded-lg text-red-600 hover:bg-red-50 transition-all">
                                <i class="fa fa-sign-out w-6 text-center mr-3"></i><span>退出登录</span>
                            </button>
                        </li>
                    </ul>
                </div>
            </div>

            <!-- 主要内容区域 -->
            <div class="md:col-span-3">
                <!-- 检测历史 -->
                <div id="detection-history" class="content-section bg-white rounded-xl shadow-md p-6 hidden">
                    <div class="text-center py-12">
                        <i class="fa fa-lock text-4xl text-gray-300 mb-3"></i>
                        <p class="text-gray-500">请先登录查看检测历史</p>
                    </div>
                    <div class="flex justify-between items-center mb-6">
                        <h3 class="text-xl font-bold text-gray-800">检测历史</h3>
                        <div class="flex gap-2">
                            <button class="px-3 py-1 border border-gray-300 rounded-lg text-sm hover:bg-gray-50">全部</button>
                            <button class="px-3 py-1 bg-gray-100 text-gray-700 rounded-lg text-sm"><i class="fa fa-calendar mr-1"></i>最近30天</button>
                        </div>
                    </div>
                    <div class="space-y-4">
                        <div class="border border-gray-200 rounded-lg p-4 hover:border-blue-200 transition-colors">
                            <div class="flex justify-between items-start mb-3">
                                <h4 class="font-medium text-gray-800">铁塔部件检测 #1024</h4>
                                <span class="px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs">已完成</span>
                            </div>
                            <div class="flex flex-wrap gap-2 text-sm text-gray-500 mb-3">
                                <span><i class="fa fa-clock-o mr-1"></i>2024-01-15 14:30</span>
                                <span><i class="fa fa-file-video-o mr-1"></i>视频文件</span>
                                <span><i class="fa fa-database mr-1"></i>12.4 MB</span>
                            </div>
                            <div class="flex items-center justify-between">
                                <div class="flex gap-2">
                                    <span class="px-2 py-0.5 bg-yellow-100 text-yellow-700 rounded-md text-xs">松动螺栓: 8</span>
                                    <span class="px-2 py-0.5 bg-red-100 text-red-700 rounded-md text-xs">腐蚀点: 12</span>
                                </div>
                                <button class="text-primary hover:text-primary/80 text-sm font-medium">查看详情 <i class="fa fa-angle-right ml-1"></i></button>
                            </div>
                        </div>
                        <div class="border border-gray-200 rounded-lg p-4 hover:border-blue-200 transition-colors">
                            <div class="flex justify-between items-start mb-3">
                                <h4 class="font-medium text-gray-800">铁塔部件检测 #1023</h4>
                                <span class="px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs">已完成</span>
                            </div>
                            <div class="flex flex-wrap gap-2 text-sm text-gray-500 mb-3">
                                <span><i class="fa fa-clock-o mr-1"></i>2024-01-14 09:15</span>
                                <span><i class="fa fa-file-image-o mr-1"></i>图片文件</span>
                                <span><i class="fa fa-database mr-1"></i>5.6 MB</span>
                            </div>
                            <div class="flex items-center justify-between">
                                <div class="flex gap-2">
                                    <span class="px-2 py-0.5 bg-yellow-100 text-yellow-700 rounded-md text-xs">松动螺栓: 3</span>
                                    <span class="px-2 py-0.5 bg-red-100 text-red-700 rounded-md text-xs">腐蚀点: 5</span>
                                </div>
                                <button class="text-primary hover:text-primary/80 text-sm font-medium">查看详情 <i class="fa fa-angle-right ml-1"></i></button>
                            </div>
                        </div>
                        <div class="border border-gray-200 rounded-lg p-4 hover:border-blue-200 transition-colors">
                            <div class="flex justify-between items-start mb-3">
                                <h4 class="font-medium text-gray-800">铁塔部件检测 #1022</h4>
                                <span class="px-2 py-1 bg-yellow-100 text-yellow-700 rounded-full text-xs">处理中</span>
                            </div>
                            <div class="flex flex-wrap gap-2 text-sm text-gray-500 mb-3">
                                <span><i class="fa fa-clock-o mr-1"></i>2024-01-14 08:45</span>
                                <span><i class="fa fa-file-video-o mr-1"></i>视频文件</span>
                                <span><i class="fa fa-database mr-1"></i>22.8 MB</span>
                            </div>
                            <div class="flex items-center justify-between">
                                <div class="text-sm text-gray-500"><i class="fa fa-spinner fa-spin mr-1"></i>正在处理中...</div>
                                <button class="text-gray-400 cursor-not-allowed text-sm">查看详情 <i class="fa fa-angle-right ml-1"></i></button>
                            </div>
                        </div>
                    </div>
                    <div class="mt-6 text-center">
                        <button id="load-more-history" class="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">
                            加载更多 <i class="fa fa-angle-down ml-1"></i>
                        </button>
                    </div>
                </div>

                <!-- 其他内容区域（默认隐藏） -->
                <div id="saved-reports" class="content-section hidden bg-white rounded-xl shadow-md p-6">
                    <h3 class="text-xl font-bold text-gray-800 mb-4">保存的报告</h3>
                    <div class="text-center text-gray-500 py-12">
                        <i class="fa fa-file-text-o text-4xl mb-3"></i>
                        <p>暂无保存的报告</p>
                    </div>
                </div>

                <div id="account-settings" class="content-section hidden bg-white rounded-xl shadow-md p-6">
                    <h3 class="text-xl font-bold text-gray-800 mb-6">账户设置</h3>
                    <form id="account-settings-form">
                        <div class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                                <input type="text" value="张三" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                                <input type="email" value="zhangsan@example.com" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">手机号</label>
                                <input type="tel" value="138****5678" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">修改密码</label>
                                <button type="button" class="text-primary hover:text-primary/80">点击修改</button>
                            </div>
                            <div>
                                <label class="flex items-center">
                                    <input type="checkbox" class="h-5 w-5 text-primary rounded border-gray-300 focus:ring-primary">
                                    <span class="ml-2 text-sm text-gray-700">接收检测结果通知</span>
                                </label>
                            </div>
                            <div>
                                <label class="flex items-center">
                                    <input type="checkbox" class="h-5 w-5 text-primary rounded border-gray-300 focus:ring-primary">
                                    <span class="ml-2 text-sm text-gray-700">允许数据分析用于模型改进</span>
                                </label>
                            </div>
                        </div>
                        <div class="mt-6 flex gap-3">
                            <button type="submit" class="px-6 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">保存设置</button>
                            <button type="button" class="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">取消</button>
                        </div>
                    </form>
                </div>

                <div id="help-center" class="content-section hidden bg-white rounded-xl shadow-md p-6">
                    <h3 class="text-xl font-bold text-gray-800 mb-4">帮助中心</h3>
                    <div class="space-y-4">
                        <div class="border-l-4 border-blue-500 pl-4 py-1">
                            <h4 class="font-medium text-gray-800 mb-1">如何上传视频进行检测？</h4>
                            <p class="text-sm text-gray-600">在检测页面，点击上传区域选择视频文件，或直接拖放视频到上传区域，然后点击"开始检测"按钮。</p>
                        </div>
                        <div class="border-l-4 border-blue-500 pl-4 py-1">
                            <h4 class="font-medium text-gray-800 mb-1">支持哪些文件格式？</h4>
                            <p class="text-sm text-gray-600">目前支持 MP4、WebM 视频格式和 JPG、PNG 图片格式，文件大小限制为50MB。</p>
                        </div>
                        <div class="border-l-4 border-blue-500 pl-4 py-1">
                            <h4 class="font-medium text-gray-800 mb-1">检测结果如何导出？</h4>
                            <p class="text-sm text-gray-600">检测完成后，在结果页面点击"导出结果"按钮，系统将生成并下载PDF格式的检测报告。</p>
                        </div>
                    </div>
                    <div class="mt-6">
                        <a href="/faq.html" class="text-primary hover:text-primary/80 flex items-center">查看更多常见问题 <i class="fa fa-arrow-right ml-1"></i></a>
                    </div>
                </div>

                <div id="about-us" class="content-section hidden bg-white rounded-xl shadow-md p-6">
                    <h3 class="text-xl font-bold text-gray-800 mb-4">关于我们</h3>
                    <p class="text-gray-600 mb-4">无。</p>
                    <div class="space-y-3 mb-4">
                        <div class="flex items-center text-gray-600">
                            <i class="fa fa-envelope-o w-8 text-center"></i>
                            <span>2079884729@qq.com</span>
                        </div>
                        <div class="flex items-center text-gray-600">
                            <i class="fa fa-phone w-8 text-center"></i>
                            <span>133-4936-6123</span>
                        </div>
                    </div>
                    <div class="mt-4">
                        <p class="text-sm text-gray-500">版本: v1.0.0</p>
                    </div>
                </div>
            </div>
        </section>
    </div>
</main>

<!-- 登录模态框 -->
<div id="login-modal" class="fixed inset-0 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4 transform transition-all">
        <div class="p-6">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-gray-900">登录</h2>
                <button id="close-login" class="text-gray-500 hover:text-gray-700"><i class="fa fa-times text-lg"></i></button>
            </div>
            <form id="login-form" class="space-y-4">
                <div>
                    <label for="login-username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                    <input type="text" id="login-username" name="login-username" required
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                </div>
                <div>
                    <label for="login-password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                    <input type="password" id="login-password" name="login-password" required
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                </div>
                <button type="submit" id="login-submit-btn" class="w-full py-2 px-4 bg-primary text-white font-medium rounded-lg hover:bg-primary/90 transition-colors">登录</button>
            </form>
            <div class="text-center mt-4">
                <span class="text-gray-600">还没有账号？</span>
                <a id="to-register" href="#" class="text-primary font-medium hover:underline">立即注册</a>
            </div>
        </div>
    </div>
</div>

<!-- 注册模态框 -->
<div id="register-modal" class="fixed inset-0 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4 transform transition-all">
        <div class="p-6">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-gray-900">注册</h2>
                <button id="close-register" class="text-gray-500 hover:text-gray-700"><i class="fa fa-times text-lg"></i></button>
            </div>
            <form id="register-form" class="space-y-4">
                <div>
                    <label for="username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                    <input type="text" id="username" name="username" required
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                </div>
                <div>
                    <label for="email" class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                    <input type="email" id="email" name="email" required
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                </div>
                <div>
                    <label for="password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                    <input type="password" id="password" name="password" required
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-all">
                </div>
                <button type="submit" id="register-submit-btn" class="w-full py-2 px-4 bg-primary text-white font-medium rounded-lg hover:bg-primary/90 transition-colors">注册</button>
            </form>
            <div class="text-center mt-4">
                <span class="text-gray-600">已有账号？</span>
                <a id="to-login" href="#" class="text-primary font-medium hover:underline">立即登录</a>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        // 核心DOM元素
        const dom = {
            // 自定义弹窗元素
            customModal: document.getElementById('customModal'),
            modalMessage: document.getElementById('modalMessage'),
            modalConfirm: document.getElementById('modalConfirm'),
            // 登录相关元素
            loginUsername: document.getElementById('login-username'),
            loginPassword: document.getElementById('login-password'),
            loginSubmitBtn: document.getElementById('login-submit-btn'),
            // 其他元素
            loginBtn: document.getElementById('login-btn'),
            loginModal: document.getElementById('login-modal'),
            registerModal: document.getElementById('register-modal'),
            closeLogin: document.getElementById('close-login'),
            closeRegister: document.getElementById('close-register'),
            toRegister: document.getElementById('to-register'),
            toLogin: document.getElementById('to-login'),
            loginForm: document.getElementById('login-form'),
            registerForm: document.getElementById('register-form'),
            registerSubmitBtn: document.getElementById('register-submit-btn'),
            regUsername: document.getElementById('username'),
            regEmail: document.getElementById('email'),
            regPassword: document.getElementById('password'),
            profileUsername: document.getElementById('profile-username'),
            profileStatus: document.getElementById('profile-status'),
            accountName: document.getElementById('account-name'),
            detectionCount: document.getElementById('detection-count'),
            loggedInContent: document.getElementById('logged-in-content'),
            logoutBtn: document.getElementById('logout-btn'),
            menuLogoutBtn: document.getElementById('menu-logout-btn'),
            menuItems: document.querySelectorAll('.menu-item:not([href="./faq.html"])'),
            contentSections: document.querySelectorAll('.content-section')
        };

        // 状态管理
        const state = {
            isLoggedIn: !!localStorage.getItem('token'),
            token: localStorage.getItem('token') || '',
            isSubmitting: false
        };

        // 初始化
        init();

        function init() {
            bindEvents();
            setupMenuNav();
            checkLogin();
            console.log('页面初始化完成，登录/注册请求已配置就绪');
            console.log('- 登录：/api/user/login');
            console.log('- 注册：/api/user/register');
            console.log('- 退出：/api/user/logout');
        }

        // 事件绑定
        function bindEvents() {
            // 自定义弹窗关闭事件
            dom.modalConfirm.addEventListener('click', () => {
                dom.customModal.classList.remove('show');
            });
            dom.customModal.addEventListener('click', (e) => {
                if (e.target === dom.customModal) {
                    dom.customModal.classList.remove('show');
                }
            });

            // 模态框控制
            dom.loginBtn.addEventListener('click', () => dom.loginModal.classList.remove('hidden'));
            dom.closeLogin.addEventListener('click', () => dom.loginModal.classList.add('hidden'));
            dom.closeRegister.addEventListener('click', () => dom.registerModal.classList.add('hidden'));

            // 切换登录/注册
            dom.toRegister.addEventListener('click', (e) => {
                e.preventDefault();
                dom.loginModal.classList.add('hidden');
                dom.registerModal.classList.remove('hidden');
            });
            dom.toLogin.addEventListener('click', (e) => {
                e.preventDefault();
                dom.registerModal.classList.add('hidden');
                dom.loginModal.classList.remove('hidden');
            });

            // 点击模态框外部关闭
            [dom.loginModal, dom.registerModal].forEach(modal => {
                modal.addEventListener('click', (e) => {
                    if (e.target === modal) modal.classList.add('hidden');
                });
            });

            // ESC关闭模态框
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape') {
                    dom.loginModal.classList.add('hidden');
                    dom.registerModal.classList.add('hidden');
                }
            });

            // 登录/注册表单提交
            dom.loginSubmitBtn.addEventListener('click', (e) => {
                e.preventDefault();
                handleLogin();
            });
            dom.registerSubmitBtn.addEventListener('click', (e) => {
                e.preventDefault();
                handleRegister();
            });

            // 退出登录
            [dom.logoutBtn, dom.menuLogoutBtn].forEach(btn => {
                btn.addEventListener('click', handleLogout);
            });
        }

        // 菜单导航
        function setupMenuNav() {
            dom.menuItems.forEach(item => {
                item.addEventListener('click', (e) => {
                    e.preventDefault();
                    dom.menuItems.forEach(i => i.classList.remove('menu-item-active'));
                    item.classList.add('menu-item-active');
                    const targetId = item.getAttribute('href').slice(1);
                    dom.contentSections.forEach(section => {
                        section.classList.toggle('hidden', section.id !== targetId);
                    });
                });
            });
        }

        // 检查登录状态
        function checkLogin() {
            if (!state.token) return setLoggedOut();
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
            if (userInfo.username) {
                setLoggedIn(userInfo);
            } else {
                localStorage.removeItem('token');
                localStorage.removeItem('userInfo');
                setLoggedOut();
            }
        }

        // 登录处理（核心修改：参数名与后端匹配）
        function handleLogin() {
            if (state.isSubmitting) return;

            const username = dom.loginUsername.value.trim();
            const password = dom.loginPassword.value.trim();

            // 空值判断
            if (!username || !password) {
                console.log('ignored call to \'alert()\'. The document is sandboxed, and the \'allow-modals\' keyword is not set.');
                dom.modalMessage.textContent = '用户名或密码为空。';
                dom.customModal.classList.add('show');
                return;
            }

            // 设置提交状态
            state.isSubmitting = true;
            dom.loginSubmitBtn.disabled = true;
            dom.loginSubmitBtn.classList.add('btn-loading');
            dom.loginSubmitBtn.textContent = '登录中...';

            // 发送登录请求（参数名已修改为login-username和login-password）
            fetch('/api/user/login', {
                method: 'POST',
                mode: 'cors',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    'login-username': username,  // 与后端data.get('login-username')匹配
                    'login-password': password   // 与后端data.get('login-password')匹配
                }),
                timeout: 10000
            })
            .then(response => {
                if (!response.ok) throw new Error(`请求失败，状态码: ${response.status}`);
                return response.json().catch(() => {
                    throw new Error('后端返回非JSON格式响应');
                });
            })
            .then(data => {
                if (data.code !== 200 || !data.data?.token) {
                    throw new Error(data.message || '登录失败，后端返回格式异常');
                }
                // 存储凭证和用户信息
                localStorage.setItem('token', data.data.token);
                localStorage.setItem('userInfo', JSON.stringify(data.data.userInfo));
                state.token = data.data.token;
                state.isLoggedIn = true;
                // 更新UI
                setLoggedIn(data.data.userInfo);
                dom.loginModal.classList.add('hidden');
                dom.modalMessage.textContent = '登录成功！';
                dom.customModal.classList.add('show');
                dom.loginForm.reset();
            })
            .catch(error => {
                console.error('登录请求失败：', error);
                dom.modalMessage.textContent = `登录失败：${error.message}`;
                dom.customModal.classList.add('show');
            })
            .finally(() => {
                state.isSubmitting = false;
                dom.loginSubmitBtn.disabled = false;
                dom.loginSubmitBtn.classList.remove('btn-loading');
                dom.loginSubmitBtn.textContent = '登录';
            });
        }

        // 注册处理
        function handleRegister() {
            if (state.isSubmitting) return;

            const username = dom.regUsername.value.trim();
            const email = dom.regEmail.value.trim();
            const password = dom.regPassword.value.trim();

            // 前端校验
            if (!username) {
                dom.modalMessage.textContent = '请输入用户名';
                dom.customModal.classList.add('show');
                return;
            }
            if (!email) {
                dom.modalMessage.textContent = '请输入邮箱';
                dom.customModal.classList.add('show');
                return;
            }
            if (!/^[\w-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9]+$/.test(email)) {
                dom.modalMessage.textContent = '请输入有效的邮箱格式';
                dom.customModal.classList.add('show');
                return;
            }
            if (!password) {
                dom.modalMessage.textContent = '请输入密码';
                dom.customModal.classList.add('show');
                return;
            }
            if (password.length < 6) {
                dom.modalMessage.textContent = '密码长度建议不少于6位';
                dom.customModal.classList.add('show');
                return;
            }

            // 设置提交状态
            state.isSubmitting = true;
            dom.registerSubmitBtn.disabled = true;
            dom.registerSubmitBtn.classList.add('btn-loading');
            dom.registerSubmitBtn.textContent = '注册中...';

            // 发送注册请求
            fetch('/api/user/register', {
                method: 'POST',
                mode: 'cors',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({ username, email, password }),
                timeout: 10000
            })
            .then(response => {
                if (!response.ok) throw new Error(`请求失败，状态码: ${response.status}`);
                return response.json().catch(() => {
                    throw new Error('后端返回非JSON格式响应');
                });
            })
            .then(data => {
                if (data.code !== 200) {
                    throw new Error(data.message || '注册失败，后端返回格式异常');
                }
                dom.modalMessage.textContent = '注册成功！请登录';
                dom.customModal.classList.add('show');
                dom.registerModal.classList.add('hidden');
                dom.loginModal.classList.remove('hidden');
                dom.registerForm.reset();
            })
            .catch(error => {
                console.error('注册请求失败：', error);
                dom.modalMessage.textContent = `注册失败：${error.message}`;
                dom.customModal.classList.add('show');
            })
            .finally(() => {
                state.isSubmitting = false;
                dom.registerSubmitBtn.disabled = false;
                dom.registerSubmitBtn.classList.remove('btn-loading');
                dom.registerSubmitBtn.textContent = '注册';
            });
        }

        // 退出登录
        function handleLogout() {
            if (state.token) {
                fetch('/api/user/logout', {
                    method: 'POST',
                    mode: 'cors',
                    credentials: 'include',
                    headers: {
                        'Authorization': `Bearer ${state.token}`,
                        'Accept': 'application/json'
                    }
                }).catch(err => {
                    console.error('退出请求失败:', err);
                });
            }

            // 清除本地状态
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            state.token = '';
            state.isLoggedIn = false;
            setLoggedOut();
            dom.modalMessage.textContent = '已退出登录';
            dom.customModal.classList.add('show');
        }

        // UI状态更新
        function setLoggedIn(userInfo) {
            dom.profileUsername.textContent = userInfo.username || '未知用户';
            dom.profileStatus.textContent = '欢迎回来';
            dom.accountName.textContent = userInfo.username || '未知用户';
            dom.detectionCount.textContent = `${userInfo.detectionCount | 0}次`;
            dom.loggedInContent.classList.remove('hidden');
            dom.loginBtn.classList.add('hidden');

            // 显示统计数据
            document.getElementById('stats-section').classList.remove('hidden');

            // 显示菜单
            document.getElementById('menu-section').classList.remove('hidden');

            // 默认只显示检测历史区域，隐藏其他内容区域
            dom.contentSections.forEach(section => {
                if (section.id === 'detection-history') {
                    section.classList.remove('hidden');
                } else {
                    section.classList.add('hidden');
                }
            });

            // 清空检测历史区域的登录提示
            const historySection = document.getElementById('detection-history');
            if (historySection.firstElementChild && historySection.firstElementChild.className.includes('text-center')) {
                historySection.removeChild(historySection.firstElementChild);
            }
        }

        function setLoggedOut() {
            dom.profileUsername.textContent = '未登录';
            dom.profileStatus.textContent = '登录后享受更多功能';
            dom.loggedInContent.classList.add('hidden');
            dom.loginBtn.classList.remove('hidden');

            // 隐藏统计数据
            document.getElementById('stats-section').classList.add('hidden');

            // 隐藏菜单
            document.getElementById('menu-section').classList.add('hidden');

            // 确保检测历史区域有登录提示
            const historySection = document.getElementById('detection-history');
            historySection.classList.add('hidden');

            // 确保检测历史区域有登录提示
            if (!historySection.firstElementChild || !historySection.firstElementChild.className.includes('text-center')) {
                // 保存原始内容
                const originalContent = historySection.innerHTML;
                // 设置登录提示
                historySection.innerHTML = `
                    <div class="text-center py-12">
                        <i class="fa fa-lock text-4xl text-gray-300 mb-3"></i>
                        <p class="text-gray-500">请先登录查看检测历史</p>
                    </div>
                `;
            }
        }
    });
</script>
</body>
</html>